package com.grand.security.springboot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	} // 配置安全拦截机制

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.csrf().disable() //屏蔽CSRF控制，即spring security不再限制CSRF
			.authorizeRequests() // 对web请求进行授权保护
			.antMatchers("/r/r1").hasAuthority("p1")
			.antMatchers("/r/r2").hasAuthority("p2")
			.antMatchers("/r/r3").access("hasAuthority('p1') and hasAuthority('p2')")
			.antMatchers("/r/**").authenticated()
			.anyRequest().permitAll()
		.and()
			.formLogin()
			.loginPage("/login-view")
			.loginProcessingUrl("/login")
			.successForwardUrl("/login-success")
			.permitAll()
		.and()
			// 默认情况下，Spring Security会为每个登录成功的用户会新建一个Session，就是ifRequired 
			.sessionManagement()
//			.expiredUrl("/login‐view?error=EXPIRED_SESSION")
			.invalidSessionUrl("/login-view?error=INVALID_SESSION")
			.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
		.and()
			.logout()
			.logoutUrl("/logout")
			.logoutSuccessUrl("/login-view?logout");
	}
}